package com.starsky.common.utils.encrypt;

import org.apache.commons.codec.binary.Base64;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

import java.io.IOException;

public class Base64Utils {
    //编码方式
    private final static String CHAR_SET = "UTF-8";

    /**
     * 编码
     *
     * @param text
     * @throws IOException
     */
    public static String encodeToString(String text) throws IOException {
        //编码
        Base64 base64 = new Base64();
        byte[] textByte = text.getBytes(CHAR_SET);
        String encodedText = base64.encodeToString(textByte);
        System.out.println(encodedText);
        return encodedText;
    }

    /**
     * 解码
     *
     * @param text
     * @throws IOException
     */
    public static String decodeToString(String text) throws IOException {
        //解码
        final Base64 base64 = new Base64();
        String decodeStr = new String(base64.decode(text), CHAR_SET);
        System.out.println(decodeStr);
        return decodeStr;
    }

    /**
     * 编码
     *
     * @param text
     * @return
     * @throws Exception
     */
    public static String encode(String text) throws Exception {

        byte[] textByte = text.getBytes(CHAR_SET);
        //编码
        BASE64Encoder encoder = new BASE64Encoder();
        String encodedText = encoder.encode(textByte);
        System.out.println(encodedText);
        return encodedText;
    }

    /**
     * 解码
     *
     * @param text
     * @return
     * @throws IOException
     */
    public static String decoder(String text) throws IOException {
        //解码
        BASE64Decoder decoder = new BASE64Decoder();
        String str = new String(decoder.decodeBuffer(text), CHAR_SET);
        return str;
    }


    public static void main(String[] args) throws Exception {

        String str = "你好";
        String encode = encode(str);
        System.out.println("encode: " + encode);

        String decoder = decoder(encode);
        System.out.println("decoder: " + decoder);

        String encodeToString = encodeToString(str);
        System.out.println("encodeToString: " + encodeToString);

        String decodeToString = decodeToString(encodeToString);
        System.out.println("decodeToString: " + decodeToString);


    }
}
